package ast

import (
	"bytes"
	"jsengine/lexer"
	"strings"
)

// Node 接口是所有AST节点的基础接口
type Node interface {
	TokenLiteral() string
	String() string
}

// Statement 接口表示语句
type Statement interface {
	Node
	statementNode()
}

// Expression 接口表示表达式
type Expression interface {
	Node
	expressionNode()
}

// Program 是AST的根节点
type Program struct {
	Statements []Statement
}

func (p *Program) TokenLiteral() string {
	if len(p.Statements) > 0 {
		return p.Statements[0].TokenLiteral()
	}
	return ""
}

func (p *Program) String() string {
	var out bytes.Buffer

	for _, s := range p.Statements {
		out.WriteString(s.String())
	}

	return out.String()
}

// LetStatement 表示let语句
type LetStatement struct {
	Token lexer.Token // token.LET
	Name  *Identifier
	Value Expression
}

func (ls *LetStatement) statementNode()       {}
func (ls *LetStatement) TokenLiteral() string { return ls.Token.Literal }
func (ls *LetStatement) String() string {
	var out bytes.Buffer

	out.WriteString(ls.TokenLiteral() + " ")
	out.WriteString(ls.Name.String())
	out.WriteString(" = ")

	if ls.Value != nil {
		out.WriteString(ls.Value.String())
	}

	out.WriteString(";")

	return out.String()
}

// VarStatement 表示var语句
type VarStatement struct {
	Token lexer.Token // token.VAR
	Name  *Identifier
	Value Expression
}

func (vs *VarStatement) statementNode()       {}
func (vs *VarStatement) TokenLiteral() string { return vs.Token.Literal }
func (vs *VarStatement) String() string {
	var out bytes.Buffer

	out.WriteString(vs.TokenLiteral() + " ")
	out.WriteString(vs.Name.String())
	out.WriteString(" = ")

	if vs.Value != nil {
		out.WriteString(vs.Value.String())
	}

	out.WriteString(";")

	return out.String()
}

// ConstStatement 表示const语句
type ConstStatement struct {
	Token lexer.Token // token.CONST
	Name  *Identifier
	Value Expression
}

func (cs *ConstStatement) statementNode()       {}
func (cs *ConstStatement) TokenLiteral() string { return cs.Token.Literal }
func (cs *ConstStatement) String() string {
	var out bytes.Buffer

	out.WriteString(cs.TokenLiteral() + " ")
	out.WriteString(cs.Name.String())
	out.WriteString(" = ")

	if cs.Value != nil {
		out.WriteString(cs.Value.String())
	}

	out.WriteString(";")

	return out.String()
}

// ReturnStatement 表示return语句
type ReturnStatement struct {
	Token       lexer.Token // token.RETURN
	ReturnValue Expression
}

func (rs *ReturnStatement) statementNode()       {}
func (rs *ReturnStatement) TokenLiteral() string { return rs.Token.Literal }
func (rs *ReturnStatement) String() string {
	var out bytes.Buffer

	out.WriteString(rs.TokenLiteral() + " ")

	if rs.ReturnValue != nil {
		out.WriteString(rs.ReturnValue.String())
	}

	out.WriteString(";")

	return out.String()
}

// ExpressionStatement 表示表达式语句
type ExpressionStatement struct {
	Token      lexer.Token // 表达式的第一个token
	Expression Expression
}

func (es *ExpressionStatement) statementNode()       {}
func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal }
func (es *ExpressionStatement) String() string {
	if es.Expression != nil {
		return es.Expression.String()
	}
	return ""
}

// BlockStatement 表示块语句
type BlockStatement struct {
	Token      lexer.Token // token.LBRACE
	Statements []Statement
}

func (bs *BlockStatement) statementNode()       {}
func (bs *BlockStatement) TokenLiteral() string { return bs.Token.Literal }
func (bs *BlockStatement) String() string {
	var out bytes.Buffer

	out.WriteString("{")
	for _, s := range bs.Statements {
		out.WriteString(s.String())
	}
	out.WriteString("}")

	return out.String()
}

// Identifier 表示标识符
type Identifier struct {
	Token lexer.Token // token.IDENT
	Value string
}

func (i *Identifier) expressionNode()      {}
func (i *Identifier) TokenLiteral() string { return i.Token.Literal }
func (i *Identifier) String() string       { return i.Value }

// IntegerLiteral 表示整数字面量
type IntegerLiteral struct {
	Token lexer.Token // token.INT
	Value int64
}

func (il *IntegerLiteral) expressionNode()      {}
func (il *IntegerLiteral) TokenLiteral() string { return il.Token.Literal }
func (il *IntegerLiteral) String() string       { return il.Token.Literal }

// FloatLiteral 表示浮点数字面量
type FloatLiteral struct {
	Token lexer.Token // token.FLOAT
	Value float64
}

func (fl *FloatLiteral) expressionNode()      {}
func (fl *FloatLiteral) TokenLiteral() string { return fl.Token.Literal }
func (fl *FloatLiteral) String() string       { return fl.Token.Literal }

// StringLiteral 表示字符串字面量
type StringLiteral struct {
	Token lexer.Token // token.STRING
	Value string
}

func (sl *StringLiteral) expressionNode()      {}
func (sl *StringLiteral) TokenLiteral() string { return sl.Token.Literal }
func (sl *StringLiteral) String() string       { return `"` + sl.Value + `"` }

// TemplateLiteral 表示模板字符串
type TemplateLiteral struct {
	Token       lexer.Token // token.TEMPLATE
	Value       string
	Expressions []Expression // 字符串插值中的表达式
	Quasis      []string     // 表达式之间的文本部分
}

func (tl *TemplateLiteral) expressionNode()      {}
func (tl *TemplateLiteral) TokenLiteral() string { return tl.Token.Literal }
func (tl *TemplateLiteral) String() string {
	var out bytes.Buffer
	out.WriteString("`")

	for i, quasi := range tl.Quasis {
		out.WriteString(quasi)
		if i < len(tl.Expressions) {
			out.WriteString("${")
			out.WriteString(tl.Expressions[i].String())
			out.WriteString("}")
		}
	}

	out.WriteString("`")
	return out.String()
}

// BooleanLiteral 表示布尔字面量
type BooleanLiteral struct {
	Token lexer.Token // token.TRUE or token.FALSE
	Value bool
}

func (bl *BooleanLiteral) expressionNode()      {}
func (bl *BooleanLiteral) TokenLiteral() string { return bl.Token.Literal }
func (bl *BooleanLiteral) String() string       { return bl.Token.Literal }

// NullLiteral 表示null字面量
type NullLiteral struct {
	Token lexer.Token // token.NULL
}

func (nl *NullLiteral) expressionNode()      {}
func (nl *NullLiteral) TokenLiteral() string { return nl.Token.Literal }
func (nl *NullLiteral) String() string       { return "null" }

// UndefinedLiteral 表示undefined字面量
type UndefinedLiteral struct {
	Token lexer.Token // token.UNDEFINED
}

func (ul *UndefinedLiteral) expressionNode()      {}
func (ul *UndefinedLiteral) TokenLiteral() string { return ul.Token.Literal }
func (ul *UndefinedLiteral) String() string       { return "undefined" }

// PrefixExpression 表示前缀表达式
type PrefixExpression struct {
	Token    lexer.Token // 前缀运算符，如 !, -, +
	Operator string
	Right    Expression
}

func (pe *PrefixExpression) expressionNode()      {}
func (pe *PrefixExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PrefixExpression) String() string {
	var out bytes.Buffer

	out.WriteString("(")
	out.WriteString(pe.Operator)
	out.WriteString(pe.Right.String())
	out.WriteString(")")

	return out.String()
}

// InfixExpression 表示中缀表达式
type InfixExpression struct {
	Token    lexer.Token // 运算符，如 +, -, *, /, ==, !=, <, >
	Left     Expression
	Operator string
	Right    Expression
}

func (ie *InfixExpression) expressionNode()      {}
func (ie *InfixExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *InfixExpression) String() string {
	var out bytes.Buffer

	out.WriteString("(")
	out.WriteString(ie.Left.String())
	out.WriteString(" " + ie.Operator + " ")
	out.WriteString(ie.Right.String())
	out.WriteString(")")

	return out.String()
}

// AssignExpression 表示赋值表达式
type AssignExpression struct {
	Token lexer.Token // =
	Left  Expression
	Value Expression
}

func (ae *AssignExpression) expressionNode()      {}
func (ae *AssignExpression) TokenLiteral() string { return ae.Token.Literal }
func (ae *AssignExpression) String() string {
	var out bytes.Buffer

	out.WriteString(ae.Left.String())
	out.WriteString(" = ")
	out.WriteString(ae.Value.String())

	return out.String()
}

// CompoundAssignExpression 表示复合赋值表达式 (+=, -=, *=, /=, %=)
type CompoundAssignExpression struct {
	Token    lexer.Token // +=, -=, *=, /=, %=
	Left     Expression
	Operator string
	Value    Expression
}

func (cae *CompoundAssignExpression) expressionNode()      {}
func (cae *CompoundAssignExpression) TokenLiteral() string { return cae.Token.Literal }
func (cae *CompoundAssignExpression) String() string {
	var out bytes.Buffer

	out.WriteString(cae.Left.String())
	out.WriteString(" " + cae.Operator + " ")
	out.WriteString(cae.Value.String())

	return out.String()
}

// PostfixExpression 表示后缀表达式 (i++, i--)
type PostfixExpression struct {
	Token    lexer.Token // token.INCREMENT or token.DECREMENT
	Left     Expression
	Operator string
}

func (pe *PostfixExpression) expressionNode()      {}
func (pe *PostfixExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PostfixExpression) String() string {
	var out bytes.Buffer

	out.WriteString("(")
	out.WriteString(pe.Left.String())
	out.WriteString(pe.Operator)
	out.WriteString(")")

	return out.String()
}

// IfExpression 表示if表达式
type IfExpression struct {
	Token       lexer.Token // token.IF
	Condition   Expression
	Consequence *BlockStatement
	Alternative *BlockStatement
}

func (ie *IfExpression) expressionNode()      {}
func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *IfExpression) String() string {
	var out bytes.Buffer

	out.WriteString("if")
	out.WriteString("(" + ie.Condition.String() + ")")
	out.WriteString(" " + ie.Consequence.String())

	if ie.Alternative != nil {
		out.WriteString("else ")
		out.WriteString(ie.Alternative.String())
	}

	return out.String()
}

// FunctionLiteral 表示函数字面量
type FunctionLiteral struct {
	Token      lexer.Token // token.FUNCTION
	Parameters []*Identifier
	Body       *BlockStatement
	Name       string
}

func (fl *FunctionLiteral) expressionNode()      {}
func (fl *FunctionLiteral) TokenLiteral() string { return fl.Token.Literal }
func (fl *FunctionLiteral) String() string {
	var out bytes.Buffer

	params := []string{}
	for _, p := range fl.Parameters {
		params = append(params, p.String())
	}

	out.WriteString(fl.TokenLiteral())
	if fl.Name != "" {
		out.WriteString(" " + fl.Name)
	}
	out.WriteString("(")
	out.WriteString(strings.Join(params, ", "))
	out.WriteString(") ")
	out.WriteString(fl.Body.String())

	return out.String()
}

// CallExpression 表示函数调用表达式
type CallExpression struct {
	Token     lexer.Token // (
	Function  Expression  // 可以是标识符或函数字面量
	Arguments []Expression
}

func (ce *CallExpression) expressionNode()      {}
func (ce *CallExpression) TokenLiteral() string { return ce.Token.Literal }
func (ce *CallExpression) String() string {
	var out bytes.Buffer

	args := []string{}
	for _, a := range ce.Arguments {
		args = append(args, a.String())
	}

	out.WriteString(ce.Function.String())
	out.WriteString("(")
	out.WriteString(strings.Join(args, ", "))
	out.WriteString(")")

	return out.String()
}

// ArrayLiteral 表示数组字面量
type ArrayLiteral struct {
	Token    lexer.Token // [
	Elements []Expression
}

func (al *ArrayLiteral) expressionNode()      {}
func (al *ArrayLiteral) TokenLiteral() string { return al.Token.Literal }
func (al *ArrayLiteral) String() string {
	var out bytes.Buffer

	elements := []string{}
	for _, el := range al.Elements {
		elements = append(elements, el.String())
	}

	out.WriteString("[")
	out.WriteString(strings.Join(elements, ", "))
	out.WriteString("]")

	return out.String()
}

// IndexExpression 表示索引表达式
type IndexExpression struct {
	Token lexer.Token // [
	Left  Expression
	Index Expression
}

func (ie *IndexExpression) expressionNode()      {}
func (ie *IndexExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *IndexExpression) String() string {
	var out bytes.Buffer

	out.WriteString("(")
	out.WriteString(ie.Left.String())
	out.WriteString("[")
	out.WriteString(ie.Index.String())
	out.WriteString("])")

	return out.String()
}

// PropertyExpression 表示属性访问表达式
type PropertyExpression struct {
	Token    lexer.Token // .
	Object   Expression
	Property Expression
}

func (pe *PropertyExpression) expressionNode()      {}
func (pe *PropertyExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PropertyExpression) String() string {
	var out bytes.Buffer

	out.WriteString(pe.Object.String())
	out.WriteString(".")
	out.WriteString(pe.Property.String())

	return out.String()
}

// ObjectLiteral 表示对象字面量
type ObjectLiteral struct {
	Token lexer.Token // {
	Pairs map[Expression]Expression
	// 添加对键类型的标记，用于支持符号和计算属性
	KeyTypes map[Expression]string // "string", "symbol", "computed"
}

func (ol *ObjectLiteral) expressionNode()      {}
func (ol *ObjectLiteral) TokenLiteral() string { return ol.Token.Literal }
func (ol *ObjectLiteral) String() string {
	var out bytes.Buffer

	pairs := []string{}
	for key, value := range ol.Pairs {
		// 处理不同类型的键
		keyStr := key.String()
		pairs = append(pairs, keyStr+": "+value.String())
	}

	out.WriteString("{")
	out.WriteString(strings.Join(pairs, ", "))
	out.WriteString("}")

	return out.String()
}

// FunctionStatement 表示函数声明语句
type FunctionStatement struct {
	Token      lexer.Token // token.FUNCTION
	Name       *Identifier
	Parameters []*Identifier
	Body       *BlockStatement
}

func (fs *FunctionStatement) statementNode()       {}
func (fs *FunctionStatement) TokenLiteral() string { return fs.Token.Literal }
func (fs *FunctionStatement) String() string {
	var out bytes.Buffer

	params := []string{}
	for _, p := range fs.Parameters {
		params = append(params, p.String())
	}

	out.WriteString("function ")
	out.WriteString(fs.Name.String())
	out.WriteString("(")
	out.WriteString(strings.Join(params, ", "))
	out.WriteString(") ")
	out.WriteString(fs.Body.String())

	return out.String()
}

// ConditionalExpression 表示三元条件表达式
type ConditionalExpression struct {
	Token       lexer.Token // token.QUESTION
	Condition   Expression
	Consequence Expression
	Alternative Expression
}

func (ce *ConditionalExpression) expressionNode()      {}
func (ce *ConditionalExpression) TokenLiteral() string { return ce.Token.Literal }
func (ce *ConditionalExpression) String() string {
	var out bytes.Buffer

	out.WriteString("(")
	out.WriteString(ce.Condition.String())
	out.WriteString(" ? ")
	out.WriteString(ce.Consequence.String())
	out.WriteString(" : ")
	out.WriteString(ce.Alternative.String())
	out.WriteString(")")

	return out.String()
}

// ForLoopStatement 表示for循环语句
type ForLoopStatement struct {
	Token     lexer.Token // token.FOR
	Init      Statement
	Condition Expression
	Update    Expression
	Body      *BlockStatement
}

func (fl *ForLoopStatement) statementNode()       {}
func (fl *ForLoopStatement) TokenLiteral() string { return fl.Token.Literal }
func (fl *ForLoopStatement) String() string {
	var out bytes.Buffer

	out.WriteString("for (")
	if fl.Init != nil {
		out.WriteString(fl.Init.String())
	} else {
		out.WriteString(";")
	}
	out.WriteString(" ")

	if fl.Condition != nil {
		out.WriteString(fl.Condition.String())
	}
	out.WriteString("; ")

	if fl.Update != nil {
		out.WriteString(fl.Update.String())
	}
	out.WriteString(") ")
	out.WriteString(fl.Body.String())

	return out.String()
}

// WhileLoopStatement 表示while循环语句
type WhileLoopStatement struct {
	Token     lexer.Token // token.WHILE
	Condition Expression
	Body      *BlockStatement
}

func (wl *WhileLoopStatement) statementNode()       {}
func (wl *WhileLoopStatement) TokenLiteral() string { return wl.Token.Literal }
func (wl *WhileLoopStatement) String() string {
	var out bytes.Buffer

	out.WriteString("while (")
	if wl.Condition != nil {
		out.WriteString(wl.Condition.String())
	}
	out.WriteString(") ")
	out.WriteString(wl.Body.String())

	return out.String()
}

// BreakStatement 表示break语句
type BreakStatement struct {
	Token lexer.Token // token.BREAK
}

func (bs *BreakStatement) statementNode()       {}
func (bs *BreakStatement) TokenLiteral() string { return bs.Token.Literal }
func (bs *BreakStatement) String() string       { return "break;" }

// ContinueStatement 表示continue语句
type ContinueStatement struct {
	Token lexer.Token // token.CONTINUE
}

func (cs *ContinueStatement) statementNode()       {}
func (cs *ContinueStatement) TokenLiteral() string { return cs.Token.Literal }
func (cs *ContinueStatement) String() string       { return "continue;" }

// ClassDeclaration 表示类声明
type ClassDeclaration struct {
	Token      lexer.Token // token.CLASS
	Name       *Identifier
	SuperClass *Identifier // 可选的父类
	Body       *ClassBody
}

func (cd *ClassDeclaration) statementNode()       {}
func (cd *ClassDeclaration) TokenLiteral() string { return cd.Token.Literal }
func (cd *ClassDeclaration) String() string {
	var out bytes.Buffer
	out.WriteString("class ")
	out.WriteString(cd.Name.String())

	if cd.SuperClass != nil {
		out.WriteString(" extends ")
		out.WriteString(cd.SuperClass.String())
	}

	out.WriteString(" ")
	out.WriteString(cd.Body.String())

	return out.String()
}

// ClassBody 表示类体
type ClassBody struct {
	Token      lexer.Token // token.LBRACE
	Methods    []*MethodDefinition
	Properties []*PropertyDefinition
}

func (cb *ClassBody) statementNode()       {}
func (cb *ClassBody) TokenLiteral() string { return cb.Token.Literal }
func (cb *ClassBody) String() string {
	var out bytes.Buffer

	out.WriteString("{\n")

	for _, method := range cb.Methods {
		out.WriteString(method.String())
		out.WriteString("\n")
	}

	for _, property := range cb.Properties {
		out.WriteString(property.String())
		out.WriteString("\n")
	}

	out.WriteString("}")

	return out.String()
}

// MethodDefinition 表示方法定义
type MethodDefinition struct {
	Token    lexer.Token // 方法名的token
	Name     *Identifier
	Params   []*Identifier
	Body     *BlockStatement
	IsStatic bool // 是否是静态方法
}

func (md *MethodDefinition) expressionNode()      {}
func (md *MethodDefinition) TokenLiteral() string { return md.Token.Literal }
func (md *MethodDefinition) String() string {
	var out bytes.Buffer

	if md.IsStatic {
		out.WriteString("static ")
	}

	out.WriteString(md.Name.String())
	out.WriteString("(")

	params := []string{}
	for _, p := range md.Params {
		params = append(params, p.String())
	}
	out.WriteString(strings.Join(params, ", "))

	out.WriteString(") ")
	out.WriteString(md.Body.String())

	return out.String()
}

// PropertyDefinition 表示属性定义
type PropertyDefinition struct {
	Token    lexer.Token
	Name     *Identifier
	Value    Expression // 可选的初始值
	IsStatic bool       // 是否是静态属性
}

func (pd *PropertyDefinition) expressionNode()      {}
func (pd *PropertyDefinition) TokenLiteral() string { return pd.Token.Literal }
func (pd *PropertyDefinition) String() string {
	var out bytes.Buffer

	if pd.IsStatic {
		out.WriteString("static ")
	}

	out.WriteString(pd.Name.String())

	if pd.Value != nil {
		out.WriteString(" = ")
		out.WriteString(pd.Value.String())
	}

	out.WriteString(";")

	return out.String()
}

// ClassExpression 表示类表达式
type ClassExpression struct {
	Token      lexer.Token // token.CLASS
	Name       *Identifier // 可选的类名
	SuperClass *Identifier // 可选的父类
	Body       *ClassBody
}

func (ce *ClassExpression) expressionNode()      {}
func (ce *ClassExpression) TokenLiteral() string { return ce.Token.Literal }
func (ce *ClassExpression) String() string {
	var out bytes.Buffer
	out.WriteString("class")

	if ce.Name != nil {
		out.WriteString(" ")
		out.WriteString(ce.Name.String())
	}

	if ce.SuperClass != nil {
		out.WriteString(" extends ")
		out.WriteString(ce.SuperClass.String())
	}

	out.WriteString(" ")
	out.WriteString(ce.Body.String())

	return out.String()
}

// NewExpression 表示new表达式
type NewExpression struct {
	Token       lexer.Token // token.NEW
	Constructor Expression
	Arguments   []Expression
}

func (ne *NewExpression) expressionNode()      {}
func (ne *NewExpression) TokenLiteral() string { return ne.Token.Literal }
func (ne *NewExpression) String() string {
	var out bytes.Buffer

	args := []string{}
	for _, a := range ne.Arguments {
		args = append(args, a.String())
	}

	out.WriteString("new ")
	out.WriteString(ne.Constructor.String())
	out.WriteString("(")
	out.WriteString(strings.Join(args, ", "))
	out.WriteString(")")

	return out.String()
}

// ThisExpression 表示this表达式
type ThisExpression struct {
	Token lexer.Token
}

func (te *ThisExpression) expressionNode()      {}
func (te *ThisExpression) TokenLiteral() string { return te.Token.Literal }
func (te *ThisExpression) String() string       { return "this" }

// SuperExpression 表示super表达式
type SuperExpression struct {
	Token lexer.Token
}

func (se *SuperExpression) expressionNode()      {}
func (se *SuperExpression) TokenLiteral() string { return se.Token.Literal }
func (se *SuperExpression) String() string       { return "super" }

// EmptyExpression 表示空表达式（例如单独的分号）
type EmptyExpression struct {
	Token lexer.Token
}

func (ee *EmptyExpression) expressionNode()      {}
func (ee *EmptyExpression) TokenLiteral() string { return ee.Token.Literal }
func (ee *EmptyExpression) String() string       { return "" }

// TryStatement 表示try语句
type TryStatement struct {
	Token   lexer.Token // token.TRY
	Body    *BlockStatement
	Catch   *CatchClause   // 可选
	Finally *FinallyClause // 可选
}

func (ts *TryStatement) statementNode()       {}
func (ts *TryStatement) TokenLiteral() string { return ts.Token.Literal }
func (ts *TryStatement) String() string {
	var out bytes.Buffer
	out.WriteString("try ")
	out.WriteString(ts.Body.String())

	if ts.Catch != nil {
		out.WriteString(" ")
		out.WriteString(ts.Catch.String())
	}

	if ts.Finally != nil {
		out.WriteString(" ")
		out.WriteString(ts.Finally.String())
	}

	return out.String()
}

// CatchClause 表示catch子句
type CatchClause struct {
	Token     lexer.Token // token.CATCH
	Parameter *Identifier // 异常参数，可选
	Body      *BlockStatement
}

func (cc *CatchClause) statementNode()       {}
func (cc *CatchClause) TokenLiteral() string { return cc.Token.Literal }
func (cc *CatchClause) String() string {
	var out bytes.Buffer
	out.WriteString("catch")

	if cc.Parameter != nil {
		out.WriteString("(")
		out.WriteString(cc.Parameter.String())
		out.WriteString(")")
	}

	out.WriteString(" ")
	out.WriteString(cc.Body.String())

	return out.String()
}

// FinallyClause 表示finally子句
type FinallyClause struct {
	Token lexer.Token // token.FINALLY
	Body  *BlockStatement
}

func (fc *FinallyClause) statementNode()       {}
func (fc *FinallyClause) TokenLiteral() string { return fc.Token.Literal }
func (fc *FinallyClause) String() string {
	var out bytes.Buffer
	out.WriteString("finally ")
	out.WriteString(fc.Body.String())

	return out.String()
}

// ThrowStatement 表示throw语句
type ThrowStatement struct {
	Token lexer.Token // token.THROW
	Value Expression  // 异常值
}

func (ts *ThrowStatement) statementNode()       {}
func (ts *ThrowStatement) TokenLiteral() string { return ts.Token.Literal }
func (ts *ThrowStatement) String() string {
	var out bytes.Buffer

	out.WriteString(ts.TokenLiteral() + " ")
	if ts.Value != nil {
		out.WriteString(ts.Value.String())
	}
	out.WriteString(";")

	return out.String()
}

// ArrowFunctionLiteral 表示箭头函数字面量
type ArrowFunctionLiteral struct {
	Token      lexer.Token // token.ARROW 或 (
	Parameters []*Identifier
	Body       Node // 可以是BlockStatement或Expression
}

func (afl *ArrowFunctionLiteral) expressionNode()      {}
func (afl *ArrowFunctionLiteral) TokenLiteral() string { return afl.Token.Literal }
func (afl *ArrowFunctionLiteral) String() string {
	var out bytes.Buffer

	params := []string{}
	for _, p := range afl.Parameters {
		params = append(params, p.String())
	}

	out.WriteString("(")
	out.WriteString(strings.Join(params, ", "))
	out.WriteString(") => ")

	if afl.Body != nil {
		out.WriteString(afl.Body.String())
	}

	return out.String()
}

// ForInLoopStatement 表示for...in循环语句
type ForInLoopStatement struct {
	Token          lexer.Token // token.FOR
	VarName        string      // 循环变量名
	HasDeclaration bool        // 是否有变量声明 (var, let, const)
	Object         Expression  // 被迭代的对象
	Body           *BlockStatement
}

func (fils *ForInLoopStatement) statementNode()       {}
func (fils *ForInLoopStatement) TokenLiteral() string { return fils.Token.Literal }
func (fils *ForInLoopStatement) String() string {
	var out bytes.Buffer

	out.WriteString("for (")

	if fils.HasDeclaration {
		out.WriteString("var ")
	}

	out.WriteString(fils.VarName)
	out.WriteString(" in ")

	if fils.Object != nil {
		out.WriteString(fils.Object.String())
	}

	out.WriteString(") ")
	out.WriteString(fils.Body.String())

	return out.String()
}

// ForOfLoopStatement 表示for...of循环语句
type ForOfLoopStatement struct {
	Token          lexer.Token // token.FOR
	VarName        string      // 循环变量名
	HasDeclaration bool        // 是否有变量声明 (var, let, const)
	Iterable       Expression  // 被迭代的可迭代对象
	Body           *BlockStatement
}

func (fols *ForOfLoopStatement) statementNode()       {}
func (fols *ForOfLoopStatement) TokenLiteral() string { return fols.Token.Literal }
func (fols *ForOfLoopStatement) String() string {
	var out bytes.Buffer

	out.WriteString("for (")

	if fols.HasDeclaration {
		out.WriteString("var ")
	}

	out.WriteString(fols.VarName)
	out.WriteString(" of ")

	if fols.Iterable != nil {
		out.WriteString(fols.Iterable.String())
	}

	out.WriteString(") ")
	out.WriteString(fols.Body.String())

	return out.String()
}

// SwitchStatement 表示switch语句
type SwitchStatement struct {
	Token   lexer.Token // token.SWITCH
	Value   Expression  // switch后面的表达式
	Cases   []*SwitchCase
	Default *SwitchCase // 默认情况（可选）
}

func (ss *SwitchStatement) statementNode()       {}
func (ss *SwitchStatement) TokenLiteral() string { return ss.Token.Literal }
func (ss *SwitchStatement) String() string {
	var out bytes.Buffer

	out.WriteString("switch ")
	out.WriteString(ss.Value.String())
	out.WriteString(" {")

	for _, c := range ss.Cases {
		out.WriteString(c.String())
	}

	if ss.Default != nil {
		out.WriteString(ss.Default.String())
	}

	out.WriteString("}")

	return out.String()
}

// SwitchCase 表示switch语句中的一个case
type SwitchCase struct {
	Token       lexer.Token // token.CASE 或 token.DEFAULT
	Condition   Expression  // case的条件表达式（对于default为nil）
	Consequence *BlockStatement
	IsDefault   bool // 是否是default case
}

func (sc *SwitchCase) statementNode()       {}
func (sc *SwitchCase) TokenLiteral() string { return sc.Token.Literal }
func (sc *SwitchCase) String() string {
	var out bytes.Buffer

	if sc.IsDefault {
		out.WriteString("default:")
	} else {
		out.WriteString("case ")
		out.WriteString(sc.Condition.String())
		out.WriteString(":")
	}

	out.WriteString(sc.Consequence.String())

	return out.String()
}
